package com.jinbo.footmessageworker;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.baoyz.widget.PullRefreshLayout;
import com.bumptech.glide.Glide;
import com.jinbo.footmessageworker.httpbean.OrderBean;
import com.jinbo.footmessageworker.httpbean.OrdersBean;
import com.jinbo.footmessageworker.httpbean.WorkerInformationBean;
import com.jinbo.footmessageworker.httpretrofit.BusinessController;
import com.jinbo.footmessageworker.httpretrofit.HttpProtocolFactory;
import com.jinbo.footmessageworker.httpretrofit.Listener;
import com.jinbo.footmessageworker.person.MyProjectsActivity;
import com.jinbo.footmessageworker.order.DealtOrderListActivity;
import com.jinbo.footmessageworker.order.HistoryOrderActivity;
import com.jinbo.footmessageworker.order.NotDealOrderListViewAdapter;
import com.jinbo.footmessageworker.person.PersonInfoActivity;
import com.jinbo.footmessageworker.remark.RemarkActivity;
import com.jinbo.footmessageworker.setting.SettingActivity;
import com.jinbo.footmessageworker.sign.SignActivity;
import com.jinbo.footmessageworker.turn.MoreTurnActivity;
import com.jinbo.footmessageworker.turn.TurnActivity;
import com.jinbo.footmessageworker.utils.LocalPreferencesHelper;
import com.jinbo.footmessageworker.view.TitleBarView;

import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;


public class NavigationActivity extends BaseActivity//AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, OnClickListener {
   /* private static final int REQUEST_IMAGE = 100;
    private static final int REQUEST_CROP = 101;
    private static final int REQUEST_TAKE_PICTURE = 102;

    //public static final String IMAGE_FILE_LOCATION = new File(MyApplication.app.getTmpDir(),"temp.jpg").getAbsolutePath();//"file:///sdcard/temp.jpg";//temp file
    //public static final File temp= new File(Environment.getExternalStorageDirectory(),"temp.jpg");
    public static final File temp= new File(MyApplication.app.getTmpDir(),"temp.jpg");
    public static final File des= new File(MyApplication.app.getTmpDir(),"head.jpg");
    public static final Uri imageUri=Uri.fromFile(temp);
    public static final Uri desUri=Uri.fromFile(des);*/
    // Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap
    //TextView word;

    private static final int REQUEST_UPDATE = 100;//更改头像后主页面修改

    // private static final int REQUEST_SETTING = 101;//设置中退出状态改变，主页面相应改变

    TextView mName;
    CircleImageView mCircleImage;
    CircleImageView img_head_view;

    private ListView listView;
    private View headerView;

    // 实例化header控件
    private ImageButton turnBtn, signBtn, serveBtn, orderBtn;

    private View updateView;
    /**
     * 列表数据适配器
     */
    NotDealOrderListViewAdapter adapter;

    List<OrderBean> orders;

    private PullRefreshLayout mPullRefreshLayout;
    String mId;


    public static final int REQUEST_NOTCONFIRM = 200;

    public static void launch(Activity activity) {
        Intent intent = new Intent(activity, NavigationActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);


        img_head_view = (CircleImageView) findViewById(R.id.icv_head);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View header = navigationView.getHeaderView(0);
        mName = (TextView) header.findViewById(R.id.textView);
        mCircleImage = (CircleImageView) header.findViewById(R.id.imageView);


        TitleBarView titleBarView = (TitleBarView) findViewById(R.id.titleBar);
        titleBarView.setCenterTitle("沐足");
        titleBarView.setLeftHeadIsVisibler(true);
        titleBarView.setListener(TitleBarView.TitleBarEnum.icv_head, this);


        mCircleImage.setOnClickListener(this);
        mName.setOnClickListener(this);


        //主界面
        headerView = LayoutInflater.from(this).inflate(R.layout.main_listview_header, null);
        listView = (ListView) findViewById(R.id.mainListView);//列表
        //adapter = new ProjectListViewAdapter(getActivity(), null);
        turnBtn = (ImageButton) headerView.findViewById(R.id.turn_btn);
        signBtn = (ImageButton) headerView.findViewById(R.id.sign_btn);
        serveBtn = (ImageButton) headerView.findViewById(R.id.serve_btn);
        orderBtn = (ImageButton) headerView.findViewById(R.id.order_btn);
        updateView=headerView.findViewById(R.id.update_view);
        listView.addHeaderView(headerView);
        // listView.addFooterView(footerView);
        adapter = new NotDealOrderListViewAdapter(this, orders,headerView);
        listView.setAdapter(adapter);
        setListener();

        mPullRefreshLayout = (PullRefreshLayout) findViewById(R.id.mainRefreshLayout);//下拉刷新，第三方控件

        mPullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {


                updateData();
            }
        });
        updateData();
        mId = MyApplication.local.getString(LocalPreferencesHelper.USER_ID);

        if (!mId.equals("")) {
            final String name = MyApplication.local.getString(mId + LocalPreferencesHelper.USER_NICKNAME);
            final String head = MyApplication.local.getString(mId + LocalPreferencesHelper.USER_HEAD_URL);
            if (!name.equals(""))
                mName.setText(name);
            if (!head.equals("")) {
                String userHead = HttpProtocolFactory.HOST_URL_USER + head;
                // new DialogUtils(NavigationActivity.this, "center", true, 0).setMessage(userHead).setButtons(null, "确定", null).create().show();
                Glide.with(NavigationActivity.this)
                        .load(userHead)
                                // .placeholder(R.mipmap.ic_launcher)
                                // .crossFade()
                        .into(mCircleImage)
                ;

                Glide.with(NavigationActivity.this)
                        .load(userHead)
                                //.placeholder(R.mipmap.ic_launcher)
                                // .crossFade()
                        .into(img_head_view);

                // Glide.clear(mCircleImage);
            }


            final String worker_name = MyApplication.local.getString(mId + LocalPreferencesHelper.USER_NAME);
            final String password = MyApplication.local.getString(mId + LocalPreferencesHelper.USER_PASSWORD);
            // String headPath=MyApplication.local.getString(id+LocalPreferencesHelper.USER_HEAD_PATH);
            BusinessController.getInstance().login(worker_name, password, new Listener<WorkerInformationBean>() {
                @Override
                public void onStart(Object... params) {

                    // showProgressDialog("请稍后...");
                }

                @Override
                public void onComplete(WorkerInformationBean result, Object... params) {
                    // dismissProgressDialog();
                    // show("登录成功" + result.user_id);
                    //   MyApplication.local.saveOrUpdate(LocalPreferencesHelper.USER_ID, result.user_id);//其他属性都应该为ID+""
                    //   String id = result.user_id;
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_SEX, result.sex);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_MOBILE, result.mobile);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_PASSWORD, password);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_NAME, worker_name);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_MAIl, result.mail);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_HEAD_URL, result.head);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_NICKNAME, result.nickname);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_AGE, result.age);
                    MyApplication.local.saveOrUpdate(mId + LocalPreferencesHelper.USER_SPECIALITY, result.speciality);
                    // NavigationActivity.launch(LoginActivity.this);
                    if (!name.equals(result.nickname))
                        mName.setText(result.nickname);
                    //String head = result.head;
                    if (!head.equals(head)) {
                        if (!TextUtils.isEmpty(result.head)) {
                            String userHeadUrl = HttpProtocolFactory.HOST_URL_USER + head;
                            // new DialogUtils(NavigationActivity.this, "center", true, 0).setMessage("刷新"+userHeadUrl).setButtons(null, "确定", null).create().show();
                            Glide.with(NavigationActivity.this)
                                    .load(userHeadUrl)
                                            //.placeholder(R.mipmap.ic_launcher)
                                            //.crossFade()

                                    .into(mCircleImage);

                            Glide.with(NavigationActivity.this)
                                    .load(userHeadUrl)
                                            // .placeholder(R.mipmap.ic_launcher)
                                            // .crossFade()
                                            //
                                    .into(img_head_view);
                            // Glide.clear(mCircleImage);
                        }
                    }
                }

                @Override
                public void onFail(final String msg, Object... params) {
                    show("网络异常,请稍后重试");
                    //当密码不一致时，执行下面的判断。。。通过msg判断
              /*  show(msg);
              LoginActivity.launch(ModifyPwdActivity.this);
                finish();
                ActivitiesHelper.getInstance().closeAll();*/
                }
            });
        }

    }

    void setListener() {
        turnBtn.setOnClickListener(this);
        signBtn.setOnClickListener(this);
        serveBtn.setOnClickListener(this);
        orderBtn.setOnClickListener(this);
    }

    //    @Override
//    public void onStart() {
//        super.onStart();
//        if(!MyApplication.local.getString("user_phone").equals("")) {
//            String userName=MyApplication.local.getString("user_name");
//            String headPath=MyApplication.local.getString("head_path");
//            if (!userName.equals("")) {
//                mName.setText(userName);
//
//            }
//            if (!headPath.equals("")) {
//                Uri imageUri = Uri.fromFile(new File(headPath));
//                mCircleImage.setImageURI(imageUri);
//                img_head_view.setImageURI(imageUri);
//            }
//        }
//        else
//        {
//            mName.setText("登录");
//            mCircleImage.setImageResource(R.drawable.head_small);
//            img_head_view.setImageResource(R.drawable.head_small);
//        }
//
//
//    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.icv_head:
                //-----点击头像
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                drawer.openDrawer(GravityCompat.START);
                break;
            case R.id.imageView:
            case R.id.textView:
                //-----点击抽屉里面的图片
                // if(MyApplication.local.getString("user_phone").equals(""))
                //        LoginActivity.launch(NavigationActivity.this);
                //else
                PersonInfoActivity.launch(this, REQUEST_UPDATE);
                break;
            case R.id.turn_btn:
                Intent intent = new Intent(this, MoreTurnActivity.class);
                startActivity(intent);
                break;
            case R.id.sign_btn:
                Intent intent1 = new Intent(this, SignActivity.class);
                startActivity(intent1);
                break;
            case R.id.serve_btn:
                Intent intent2 = new Intent(this, RemarkActivity.class);
                startActivity(intent2);
                break;
            case R.id.order_btn:
                Intent intent3 = new Intent(this, DealtOrderListActivity.class);
                startActivity(intent3);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here
        int id = item.getItemId();
        Intent intent = null;
 /*       if (id == R.id.nav_order) {
            // Handle the camera action
           // word.setText("1");
            //  Toast.makeText(this,"1",Toast.LENGTH_LONG).show();
            intent=new Intent(this,TurnActivity.class);
            startActivity(intent);

        } else*/
        if (id == R.id.nav_history) {
            intent = new Intent(this, HistoryOrderActivity.class);
            startActivity(intent);
            //word.setText("2");
            // Toast.makeText(this,"2",Toast.LENGTH_LONG);
        } else if (id == R.id.nav_share) {
            intent = new Intent(this, MyProjectsActivity.class);
            startActivity(intent);
            // word.setText("3");
            // Toast.makeText(this,"3",Toast.LENGTH_LONG);
        } else if (id == R.id.nav_manage) {
            // intent=new Intent(this,SettingActivity.class);
            //startActivity(intent);
            SettingActivity.launch(this);//,REQUEST_SETTING);
            // word.setText("4");
            // Toast.makeText(this,"4",Toast.LENGTH_LONG);
        } else if (id == R.id.nav_about) {
            intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
            // word.setText("5");
            // Toast.makeText(this, "5", Toast.LENGTH_LONG);
        } /*else if (id == R.id.nav_send) {
            word.setText("6");
            //Toast.makeText(this,"6",Toast.LENGTH_LONG);
        }*/
        //if(intent!=null)
//             startActivity(intent);
//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        drawer.closeDrawer(GravityCompat.START);
        return false;
    }


    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.default_amin_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_UPDATE) {
                // new DialogUtils(NavigationActivity.this, "center", true, 0).setMessage("fanhui").setButtons(null, "确定", null).create().show();
                String name = MyApplication.local.getString(mId + LocalPreferencesHelper.USER_NICKNAME);
                String head = MyApplication.local.getString(mId + LocalPreferencesHelper.USER_HEAD_URL);
                //data.getStringExtra("name");
                if (!name.equals(""))
                    mName.setText(name);
                if (!head.equals("")) {
                    String userHead = HttpProtocolFactory.HOST_URL_USER + head;
                    // new DialogUtils(NavigationActivity.this, "center", true, 0).setMessage(userHead).setButtons(null, "确定", null).create().show();
                    Glide.with(NavigationActivity.this)
                            .load(userHead)
                                    // .crossFade()
                                    //  .placeholder(R.drawable.head_small)
                            .into(mCircleImage);

                    Glide.with(NavigationActivity.this)
                            .load(userHead)
                                    // .crossFade()
                                    //  .placeholder(R.drawable.head_small)
                            .into(img_head_view);
                    // Glide.clear(mCircleImage);
                }

            }
            if (requestCode == REQUEST_NOTCONFIRM) {
                updateData();
            }
        }
    }

    void updateData() {
        String worker_id = MyApplication.local.getString(LocalPreferencesHelper.USER_ID);
        BusinessController.getInstance().notConfirmOrder(worker_id, new Listener<OrdersBean>() {
            @Override
            public void onStart(Object... params) {
                //showProgressDialog("请稍后...");
                //mLoadView.setVisibility(View.VISIBLE);
                mPullRefreshLayout.setRefreshing(true);
                //mLoadView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onComplete(OrdersBean result, Object... params) {
                //dismissProgressDialog();
                mPullRefreshLayout.setRefreshing(false);
                // mLoadView.setVisibility(View.GONE);
                //mCallBacks1.change(result.orders);
                // mCallBacks2.change(result.orders);
                if(result.orders.size()==0)
                    updateView.setVisibility(View.VISIBLE);
                else {
                    updateView.setVisibility(View.GONE);
                    adapter.setorders(result.orders);
                }


            }

            @Override
            public void onFail(final String msg, Object... params) {
                // mLoadView.setVisibility(View.VISIBLE);
                //dismissProgressDialog();
                //mLoadView.setVisibility(View.GONE);
                mPullRefreshLayout.setRefreshing(false);
                if (TextUtils.isEmpty(msg)) {
                } else {
                    show(msg);
                }
            }
        });
    }
}
